//
//  XJPictureView.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/26.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit
import SVProgressHUD

class XJPictureView: UICollectionView {
    
    //添加图片的闭包
    var selectedPicClosure: (()->())?
    
    //图片数组
    lazy var imageArr: [UIImage] = []

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        self .setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
      self.backgroundView = UIImageView(image: UIImage(named: "compose_toolbar_background"))
        
        registerClass(XJPictureViewCell.self, forCellWithReuseIdentifier: "pictureCell")
        dataSource = self
        delegate = self
    }
    
    /**
     供外界添加图片
     */
    func addImage(img: UIImage) {
        
        if imageArr.count < 9{
            imageArr.append(img)
            self.reloadData()
            
        }else{
            SVProgressHUD.showErrorWithStatus("数量已达上限")
        }
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        let margin: CGFloat = 5
        let itemWH = (self.frame.width - 2 * margin)/3
        layout.itemSize = CGSizeMake(itemWH, itemWH)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
    }
}

extension XJPictureView: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.hidden = imageArr.count == 0
        return imageArr.count + ((imageArr.count == 0 || imageArr.count == 9) ? 0 : 1)
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pictureCell", forIndexPath: indexPath) as! XJPictureViewCell
        
        
        if indexPath.item == imageArr.count {
            //最后一张
            cell.img = nil
        }else{
            
            cell.img = imageArr[indexPath.item]
        }
        
        //删除按钮执行闭包,移除图片,刷新数据
        cell.deleteButtonClosure = { [weak self] in
            
            self?.imageArr.removeAtIndex(indexPath.item)
            self?.reloadData()
        }
        
        return cell
    }
    
    //监听cell点击
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //点击的是最后一个item
        if indexPath.item == imageArr.count {
        
            selectedPicClosure?()
        }
    }
    
}

// MARK: - 自定义cell
class XJPictureViewCell: UICollectionViewCell {
    
    
    //删除按钮闭包
    var deleteButtonClosure: (()->())?
    
    var img: UIImage?{
        
        didSet{
            if img == nil {
                picImg.image = UIImage(named: "compose_pic_add")
                deleteBtn.hidden = true
                
            }else{
                picImg.image = img
                deleteBtn.hidden = false
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 布局界面,添加子控件及约束
    private func setupUI() {
        
        contentView.addSubview(picImg)
        contentView.addSubview(deleteBtn)
        
        picImg.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(self)
        }
    }
    
    /**
     删除按钮的点击事件
     */
    @objc private func didClickDeleBtn() {
    
        deleteButtonClosure?()
    }
    
    // MARK: - 懒加载控件
    //图片
    private lazy var picImg: UIImageView = UIImageView()
    
    //删除按钮
    private lazy var deleteBtn: UIButton = {
    
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        
        btn.addTarget(self, action: "didClickDeleBtn", forControlEvents: .TouchUpInside)
        
        return btn
    }()
    
}



